package com.ruoyi.web.service.impl;


import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.web.domain.Ca;
import com.ruoyi.web.mapper.CaLoginMapper;
import com.ruoyi.web.service.CaLoginService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class CaLoginServiceImpl implements CaLoginService {

    @Autowired
    private CaLoginMapper caLoginMapper;

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    @Override
    public int insertCa(Ca ca) {
        String password = ca.getPassword();
        String Md5Password = Md5Utils.hash(password);
        ca.setPassword(Md5Password);

        String uuid = UUID.randomUUID().toString();
        ca.setEncryptedtoken(uuid);
        return caLoginMapper.insertCa(ca);
    }

    @Override
    public boolean findBy(String number) {
        caLoginMapper.selectByNumber(number);
        return true;
    }

    @Override
    public Ca loginByPhoneNumber(String phoneNumber) {
        Ca ca = caLoginMapper.loginByPhoneNumber(phoneNumber);
        return ca;
    }

    @Override
    public boolean verification(String phoneNumber, RedisTemplate redisTemplate,String captcha) {
        String o = (String) redisTemplate.opsForValue().get(phoneNumber);
        if (o.equals(captcha)){
            return true;
        }
        return false;
    }

    @Override
    public String createToken(Ca ca) {
        Map<String,Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY,ca);

        String token = Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis()+24*60*60*1000))
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

}
